package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器类型  pre,routing,post,error
    @Override
    public String filterType() {
//        return "pre";或者
        return FilterConstants.PRE_TYPE;
    }

    //设置过滤器添加的位置顺序号
    @Override
    public int filterOrder() {
        return 6;
    }
    //判断对当前请求,是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /**
         * 如果调用商品,必须登陆才能操作
         * 调用其他服务不必登陆
         */

        //得到当前请求的后台服务的服务id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //判断服务id是否是"item-service"
        return "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //得到request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        // 如果没有token

        if (StringUtils.isBlank(token)){
            //1. 阻止继续执行
            ctx.setSendZuulResponse(false);
            //2.向客户端返回响应"没有登陆"
            //jsonResult{code:401,msg:"not login",data:null}
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN)
                    .msg("Not login!").toString();
            ctx.addZuulResponseHeader("Content-type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
      return null;//当前zuul版本中,返回值没有作用
    }
}
